import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:baidu_map_plugin/baidu_map.dart';

class MaPpage extends StatefulWidget {
  @override
  _MaPpageState createState() => _MaPpageState();
}

class _MaPpageState extends State<MaPpage> {
  String _platformVersion = 'Unknown';
  BaiDuMapViewPlatformViewController platformControler;

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformVersion = await BaiduMapviewManager.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: Center(
        child: Container(
          // width: MediaQuery.of(context).size.width,
          // height: MediaQuery.of(context).size.height,
          child: BaiduMapView(
            hexColor: "",
            androidPlatform: AndroidPlatform(
              androidPlatformViewCreatedCallback: _createCallBack,
              //选中的回调
              onSelectedOverlayOption: (OverlayOption option) {
                debugPrint(
                    "_MyAppState--onSelectedOverlayOption():option=${option.toJson()}");
              },
            ),
          ),
        ),
      ),
    );
  }

  void _createCallBack(BaiDuMapViewPlatformViewController controller) {
    setState(() {
      platformControler = controller;
      setMapCenter();
      addMarkers();
    });
  }

  /// 设定地图显示中心
  void setMapCenter() {
    platformControler.setMapViewCenter(22.576752653796447, 113.94312524555225);
  }

  /// 添加标注
  /// 传输数据为 [OverlayOption]
  void addMarkers() {
    FlutterNativeBaiDuViewModel androidMapNativeMode =
        FlutterNativeBaiDuViewModel();
    List<OverlayOption> androidMapLatLngList = List.generate(4, (int i) {
      return OverlayOption(
        latitude: 22.5758170540645 + i * 0.001,
        longitude: 113.94350914911085 + i * 0.002,
        text: "7栋B座-正门前方$i",
        id: '$i',
        isSelect: true,
      );
    });
    platformControler.updateMapView(
        androidMapNativeMode..overlayOptions = androidMapLatLngList);
  }

  @override
  void dispose() {
    super.dispose();
    print("flutter 地图界面释放");
  }
}
